<?php
/**
 *  @department : Commercial development.
 *  @description : This file is part of [example].
 *  example all rights reserved.
 */
namespace app\traits;

trait JsonResponse
{
    /**
     * 统一JSON接口数据返回格式 .
     */
    protected function jsonReturnData($data,  $message = '', $code = null)
    {
        return $this->jsonResponseData(true, (empty($code) ? 200 : $code), (empty($message) ? '请求成功' : $message), $data);
    }

    /**
     * 统一JSON接口数据返回格式 .
     */
    protected function jsonSuccess( $message,  $code  = null)
    {
        return $this->jsonResponseData(true, (empty($code) ? 200 : $code), (empty($message) ? '操作成功' : $message));
    }

    /**
     * 统一JSON异常业务返回格式 异常.
     */
    protected function jsonError( $message, $code  = null)
    {
        return $this->jsonResponseData(false, (empty($code) ? 500 : $code), $message);
    }

    /**
     * 返回一个JSON数组数据。
     */
    private function jsonResponseData($status, $code,  $message = '', $data = [])
    {
        //增加返回字段的限制条件
        if ($status) {
            $json_content = [
                'status' => true,
                'code'   => $code,
                'msg'    => $message,
                'data'   => $data,
                'message'=> $message,
            ];
        } else {
            $json_content = [
                'status' => false,
                'code'   => $code,
                'msg'    => $message,
                'message'=> $message,
            ];
        }

        return json($json_content);
    }

        /**
     * 统一JSON接口数据返回格式 .
     */
    protected function jsonReturn($data,  $message = '', $code = null)
    {
        return $this->jsonResponse(true, (empty($code) ? 200 : $code), (empty($message) ? '请求成功' : $message), $data);
    }

    /**
     * 返回一个自定义键值的数组 -- 兼容部分项目。
     */
    private function jsonResponse($status, $code,  $message = '', $data)
    {
        //增加返回字段的限制条件
        if ($status) {

            $json_content = [
                'status' => true,
                'code'   => $code,
                'msg'    => $message,
                'message'=> $message,
            ];
        } else {
            $json_content = [
                'status' => false,
                'code'   => $code,
                'msg'    => $message,
                'message'=> $message,
            ];
        }

        return json(array_merge($json_content, $data));
    }
}
